//
//  HJWebSocketResponseManager.m
//  KaiChat
//
//  Created by lx on 2023/10/24.
//

#import "HJWebSocketResponseManager.h"
#import "HJWebSocketManager.h"
#import "HJChatMessageModel.h"
#import "HJDataPacketHeader.h"
#import "HJChatSessionModel.h"
#import "HJChatGroupModel.h"
#import "HJGroupMemberModel.h"
#import "HJIM.h"
#import "HJUserNotifications.h"
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>

@interface HJWebSocketResponseManager()<HJWebSocketManagerDelegate>

@property (nonatomic, assign) NSInteger lastTimestep;

@end


static HJWebSocketResponseManager *_webSocketResponseManager = nil;

@implementation HJWebSocketResponseManager

+ (instancetype)shareManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _webSocketResponseManager = [[self alloc] init];
        [[HJWebSocketManager shareManager] addDelegate:_webSocketResponseManager];
    });
    return _webSocketResponseManager;
    
}

+ (void)load {
    [HJWebSocketResponseManager shareManager];
}

- (void)webSocket:(HJWebSocketManager *)webSocketManager didReceiveMessage:(NSDictionary *)message {
    
    [self comfirmMessageWithMessage:message];
    
    //31就更新91的消息, 直接发通知更新就行
    //如果收到31 的消息, 就查找91的消息, 然后把31的状态消息更新为91消息的转账状态, 让后不保存31消息, 31消息可以保存,这个的消息id就是转账信息里面的 msg_id
    
    dispatch_async_serial_queue(^{
        
        HJChatMessageModel *messageModel = [HJChatMessageModel messageModelWithDict:message];
        
        if (messageModel.systemMsgType == HJChatSystemMsgTypeApplyFridend) {
            [HJIM.shareIM.userManager loadApplyCountComplete:nil];
            return;
        }
        
        if (messageModel.systemMsgType == HJChatSystemMsgTypeApplyFridendAgree) {
            [[NSNotificationCenter defaultCenter] postNotificationName:applyFridendAgreeNotification object:nil];
        }
        
        if (messageModel.systemMsgType == HJChatSystemMsgTypeDisbandGroup || messageModel.systemMsgType == HJChatSystemMsgTypeApplyJoinGroup) {
            dispatch_async_main_queue(^{
                [[NSNotificationCenter defaultCenter] postNotificationName:groupSystemNotification object:messageModel];
            });
            return;
        }
        
        if (messageModel.messageType == HJMessageTypeTransfer && messageModel.systemMsgType == HJChatSystemMsgTypeTransfer) {
            dispatch_async_sql_queue(^{
                HJChatMessageModel *transferMessageModel = [HJIM.shareIM.messageManager queryMessageBySessionId:messageModel.sessionId messageId:messageModel.msgId];
                transferMessageModel.orderStatus = messageModel.orderStatus;
                [transferMessageModel bg_saveOrUpdate];
                dispatch_async_main_queue(^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:sendMessageCompleteNotification object:transferMessageModel];
                });
            });
            return;
        }
        
        [HJIM.shareIM.messageManager handleSystemMsg:messageModel];
        
        if (!messageModel) return;
        if (messageModel.chatType != HJChatTypeOfficial && messageModel.sessionId.intValue == 0) return;
        
        
        if (isEmptyString(messageModel.content) && (messageModel.messageType == HJMessageTypeText || messageModel.messageType == HJMessageTypeSystem)) return;
        
        //改下IM的逻辑, 如果是在线的消息, 判断是不是新的回话, 如果是新的回话, 就查询, 如果不是新的回话就查数据库
        //判断回话的头像和昵称或者是userId是空的, 就查询
        //然后根据消息来首次来加载群信息或者是个人信息做个数据缓存
        //在回话的后面判断如果头像或者是没有信息, 就去根据个人资料去查询
        
        messageModel.receiverAvatar = HJUserInfo.avatar;
        messageModel.receiverNickname = HJUserInfo.nickname;
        messageModel.receiverId = HJUserInfo.userId;

        HJChatSessionModel *oldSessionModel = [HJIM.shareIM.conversationManager getSimpleConversationBySessionId:messageModel.sessionId];
        BOOL isNewSession = isEmptyString(oldSessionModel.sessionId);
        
        if (!isNewSession && messageModel.systemMsgType == HJChatSystemMsgTypeModifyGroupName && messageModel.groupName) {
            oldSessionModel.sessionName = messageModel.groupName;
        }
        
        if (messageModel.chatType == HJChatTypeOfficial) {
            
            if (isEmptyString(oldSessionModel.sessionName) || isEmptyString(oldSessionModel.sessionAvatar)) {
                [HJIM.shareIM.chatManager queryOfficialAccountCompletion:^(NSArray * _Nullable datas) {
                    
                    HJChatSessionModel *sessionModel = nil;
                    for (HJChatSessionModel *model in datas) {
                        if ([model.sessionId isEqualToString:messageModel.sessionId]) {
                            sessionModel = model;
                            break;
                        }
                    }
                    
                    messageModel.sessionAvatar = sessionModel.sessionAvatar;
                    messageModel.sessionName = sessionModel.sessionName;
                    [self buildConversationWithMessageModel:messageModel chatSessionModel:sessionModel isNewSession:isNewSession];
                }];
            } else {
                [self buildConversationWithMessageModel:messageModel chatSessionModel:oldSessionModel isNewSession:isNewSession];
            }
            
        } else if (messageModel.chatType == HJChatTypeSingle) {
            
            if (isEmptyString(oldSessionModel.sessionAvatar) || isEmptyString(oldSessionModel.sessionName) || isEmptyString(oldSessionModel.sessionUserd)) {
                
                [HJIM.shareIM.conversationManager loadConversatioInfoWithSessionId:messageModel.sessionId type:messageModel.chatType completion:^(HJChatSessionModel * _Nonnull sessionModel) {
                    
                    if (sessionModel) {
                        messageModel.senderAvatar = sessionModel.sessionAvatar;
                        messageModel.senderNickname = sessionModel.sessionName;
                        messageModel.sessionUid = sessionModel.uid;
                        messageModel.sessionUserd = sessionModel.sessionUserd;
                        messageModel.sessionName = sessionModel.sessionName;
                        messageModel.sessionUserd = sessionModel.sessionUserd;
                    }
                    
                    [self buildConversationWithMessageModel:messageModel chatSessionModel:sessionModel isNewSession:isNewSession];
                    
                }];
            } else {
                [self buildConversationWithMessageModel:messageModel chatSessionModel:oldSessionModel isNewSession:isNewSession];
            }
            
        } else {
            
            if (isEmptyString(oldSessionModel.sessionAvatar) || isEmptyString(oldSessionModel.sessionName)) {
                
                [HJIM.shareIM.conversationManager loadConversatioInfoWithSessionId:messageModel.sessionId type:messageModel.chatType completion:^(HJChatSessionModel * _Nonnull sessionModel) {
                    
                    if (sessionModel) {
                        messageModel.sessionName = sessionModel.sessionName;
                        messageModel.sessionAvatar = sessionModel.sessionAvatar;
                    }
                    
                    [self buildConversationWithMessageModel:messageModel chatSessionModel:sessionModel isNewSession:isNewSession];
                }];
            } else {
                [self buildConversationWithMessageModel:messageModel chatSessionModel:oldSessionModel isNewSession:isNewSession];
            }
        }
    });
    
}

- (void)buildConversationWithMessageModel:(HJChatMessageModel *)messageModel chatSessionModel:(HJChatSessionModel *)chatSessionModel isNewSession:(BOOL)isNewSession {
        
    dispatch_async_sql_queue(^{
        
        [self updateUserInfoWithMessageModel:messageModel];
        
        BOOL isNewMessage = [HJIM.shareIM.messageManager isNewMessageBySessionId:messageModel.sessionId messageId:messageModel.msgId];
        
        HJChatSessionModel *sessionModel = [HJChatSessionModel sessionModelWithMessageModel:messageModel];
        sessionModel.isSendMsg = @"2";
        if (chatSessionModel) {
            sessionModel.isTop = chatSessionModel.isTop;
            sessionModel.isMute = chatSessionModel.isMute;
            sessionModel.sessionUserd = chatSessionModel.sessionUserd;
            sessionModel.sessionUid = chatSessionModel.sessionUid;
            sessionModel.sessionName = chatSessionModel.sessionName;
            sessionModel.sessionAvatar = chatSessionModel.sessionAvatar;
        }
        
        if (isNewMessage) {
            if (sessionModel.messageType == HJMessageTypeNotice) {
                NSDictionary *systemMsgDict = [messageModel.msg mj_JSONObject];
                NSString *operatorUserId = toString(systemMsgDict[@"operator"][@"user_id"]);
                if (!TJIM_isSelf(operatorUserId)) {
                    sessionModel.hasNotice = @"1";
                    [sessionModel bg_saveOrUpdate];
                }
            }
            
            if (messageModel.countedUnreadCount) {
                sessionModel.unReadCount = @"1";
            }
        }
        
        [HJIM.shareIM.conversationManager addConversation:sessionModel];
        [messageModel downloadVoice];
        if (isNewMessage) {
            [messageModel bg_save];
            [[NSNotificationCenter defaultCenter] postNotificationName:receiveNewMessageNotification object:messageModel];
            [messageModel previewLink];
        } else {
            [messageModel bg_saveOrUpdate];
        }
        
        if (!sessionModel.isMute.boolValue) {
            dispatch_async_main_queue(^{
                [HJUserNotifications pushNotificationsWithSessionModel:sessionModel messageModel:messageModel];
            });
        }
        
        if (isNewSession) {
            [self cacheUserOrGroupDataWithMessageModel:messageModel];
        }
    });
    
}

- (void)cacheUserOrGroupDataWithMessageModel:(HJChatMessageModel *)messageModel {
    
    if (messageModel.chatType == HJChatTypeSingle) {
        
        NSString *userId = messageModel.senderId;
        if (messageModel.chatType == HJMessageTypeTransfer && TJIM_isSelf(messageModel.senderId)) {
            userId = messageModel.sessionUserd;
        }
        
        [HJIM.shareIM.userManager loadFriendInfoWithUserId:userId complete:^(HJChatFriendModel * _Nullable model) {}];
        return;
    }
    
    if (messageModel.chatType == HJChatTypeGroup) {
        [HJIM.shareIM.groupManager loadGroupInfoByGroupId:messageModel.groupId completion:^(HJChatGroupModel * _Nullable groupModel) {}];
        return;
    }
}


- (void)updateUserInfoWithMessageModel:(HJChatMessageModel *)messageModel {
    
    NSString *userId = messageModel.senderId;
    if (messageModel.chatType == HJMessageTypeTransfer && TJIM_isSelf(messageModel.senderId)) {
        userId = messageModel.sessionUserd;
    }
    
    HJChatUserModel *userModel = [HJIM.shareIM.userManager queryUserInfoByUserId:userId];
    
    BOOL isChange = NO;
    if (userModel) {
        if (userModel.showName && ![messageModel.senderNickname isEqualToString:userModel.showName]) {
            isChange = YES;
        }
        if (userModel.avatar && ![messageModel.senderAvatar isEqualToString:userModel.avatar]) {
            isChange = YES;
        }
        
        if (isChange) {
            messageModel.userInfoChange = isChange;
        }
    }
    
    if (isChange) {
        userModel.avatar = messageModel.senderAvatar;
        userModel.nickname = messageModel.senderNickname;
        [userModel bg_saveOrUpdate];
        
        if (messageModel.chatType == HJChatTypeSingle) {
            HJChatFriendModel *fridendModel = [HJIM.shareIM.userManager queryFriendInfoByFriendId:messageModel.senderId];
            fridendModel.avatar = messageModel.senderAvatar;
            fridendModel.nickname = messageModel.senderNickname;
            [fridendModel bg_saveOrUpdate];
        }
    }
}





- (void)comfirmMessageWithMessage:(NSDictionary *)message {
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:message[@"seq_id"] forKey:@"seq_id"];
    [dict setValue:message[@"rcv_uid"] forKey:@"rcv_id"];
    [dict setValue:message[@"association_msg_id"] forKey:@"association_id"];
    
    NSInteger op = [message[@"op"] intValue];
    if (op == HJChatTypeSingle) {
        [dict setValue:@1 forKey:@"Kind"];
    } else if (op == HJChatTypeGroup) {
        [dict setValue:@2 forKey:@"Kind"];
    } else if (op == 3000) {
        [dict setValue:@3 forKey:@"Kind"];
    }
    NSData *bodyData = dict.mj_JSONData;
    HJDataPacketHeader *packetHeader = [[HJDataPacketHeader alloc] initWithBodyData:bodyData seq:[message[@"seq_id"] longLongValue] operation:20];
    NSData *packetData = HJMakePacketData(packetHeader.data, bodyData);
    [[HJWebSocketManager shareManager] sendData:packetData error:nil];
}

- (void)webSocket:(HJWebSocketManager *)webSocketManager didConnectFail:(NSError *)error {
    
    
}


- (void)dealloc {
    [[HJWebSocketManager shareManager] removeDelegate:self];
}


- (void)playSystemSound {
    dispatch_async_main_queue(^{
        NSString *soundIDName = @"messageSound.mp3";
        NSString *urlString = [NSString stringWithFormat:@"%@",[[NSBundle mainBundle] pathForResource:soundIDName ofType:nil]];
        NSURL *url = [NSURL URLWithString:urlString];
        static SystemSoundID soundID = 10000;
        AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)url, &soundID);
        AudioServicesPlaySystemSound(soundID);
    });
}



@end
